package com.netease.nie.base.entity;

import java.io.File;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;

import org.apache.commons.lang.ArrayUtils;

import com.netease.nie.base.exceptions.UnexpectedException;
import com.netease.nie.base.mybatis.common.Entity;
import com.netease.nie.base.utils.ClassUtils;

/**
 * 
 * @author KingsHunter
 * @createDate July 13th,2016
 * 
 */
public class EntityManager {

	private static final String PATH = "com/netease/nie/model/";
	
	private Map<String, Entity> entitySet;

	private static EntityManager entityManager = new EntityManager();

	private EntityManager() {
		init();
	}

	public static EntityManager getInstance() {
		return entityManager;
	}

	public void init() {
		generateEntitySet();
		
	}

	/**
	 * 
	 * @param className
	 * @return
	 */
	public Entity getEntity(String className) {
		if (!entitySet.containsKey(className)) {
			return null;
		}
		return entitySet.get(className);
	}
	
	public Map<String, Entity> generateEntitySet() {
		Enumeration<URL> enumerations = ClassUtils.getInstance().getResources(PATH);
		URL url = null;
		if (enumerations != null) {
			Entity entity = null;
			File directory = null;
			String fullName = null;
			String packName = null;
			while (enumerations.hasMoreElements()) {
				url = enumerations.nextElement();
				directory = new File(url.getPath());
				String[] fileNameArr = directory.list();
				if (ArrayUtils.isEmpty(fileNameArr))
					throw new UnexpectedException("no files have been found");
				packName = PATH.substring(1).replaceAll("/", ".");
				for (String fileName : fileNameArr) {
					entity = new Entity();
					fullName = packName + fileName.substring(0, fileName.lastIndexOf("."));
					entity.setFullName(fullName);
				}
			}
		}
		return null;
	}
}
